"""
FastAPI主应用
"""

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import time
import traceback
import os

from .api.router import router as api_router
from .core.config import settings
from .core.logging import setup_logging

# 设置日志
logger = setup_logging()

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description=settings.APP_DESCRIPTION,
    version=settings.APP_VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加请求处理中间件
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    """
    添加处理时间头中间件
    """
    start_time = time.time()
    request_id = f"req_{int(time.time() * 1000)}"
    logger.debug(f"[{request_id}] 收到请求: {request.method} {request.url.path} - 查询参数: {dict(request.query_params)}")
    
    try:
        response = await call_next(request)
        process_time = time.time() - start_time
        logger.debug(f"[{request_id}] 请求处理完成 - 状态码: {response.status_code} - 处理时间: {process_time:.3f}秒")
        response.headers["X-Process-Time"] = str(process_time)
        return response
    except Exception as e:
        logger.error(f"[{request_id}] 请求处理出错: {str(e)}")
        logger.error(traceback.format_exc())
        return JSONResponse(
            status_code=500,
            content={"detail": str(e)},
        )

# 添加API路由
app.include_router(api_router, prefix=settings.API_PREFIX)

# 根路由
@app.get("/")
async def root():
    """
    根路由
    """
    return {
        "name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "description": settings.APP_DESCRIPTION,
        "docs_url": "/docs",
    }

# 健康检查路由
@app.get("/api/health")
async def health_check():
    """
    健康检查路由
    """
    return {"status": "ok", "version": settings.APP_VERSION}

# 启动事件
@app.on_event("startup")
async def startup_event():
    """
    应用启动事件
    """
    logger.info(f"{settings.APP_NAME} v{settings.APP_VERSION} 启动")
    
    # 检查环境变量
    logger.info(f"主机: {settings.HOST}, 端口: {settings.PORT}, 调试模式: {settings.DEBUG}")
    logger.info(f"日志级别: {settings.LOG_LEVEL}")
    
    # 检查OpenAI配置
    if not settings.OPENAI_API_KEY or settings.OPENAI_API_KEY == "your_openai_api_key" or settings.OPENAI_API_KEY == "your_openai_api_key_here":
        logger.warning("⚠️ 未设置有效的OpenAI API密钥，请在.env文件中设置OPENAI_API_KEY")
    else:
        logger.info(f"OpenAI模型: {settings.OPENAI_MODEL}, API URL: {settings.OPENAI_BASE_URL}")
    
    # 检查工作目录和.env文件
    logger.info(f"当前工作目录: {os.getcwd()}")
    if os.path.exists(".env"):
        logger.info("✅ .env文件存在")
    else:
        logger.warning("⚠️ .env文件不存在，请从env.example创建")
        
    # 检查日志目录
    if not os.path.exists("logs"):
        logger.info("创建日志目录")
        os.makedirs("logs", exist_ok=True)

# 关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """
    应用关闭事件
    """
    logger.info(f"{settings.APP_NAME} v{settings.APP_VERSION} 关闭")
    
    # 这里可以添加其他关闭任务，如关闭数据库连接等

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG
    ) 